package com.baosight.risk.service.rifi.impl;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.rifi.RifiRiskFinishService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtzy.IXtzyRoleUserService;
import com.baosight.risk.base.redis.BaseRedis;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.riaa.RiaaEvaluateMapper;
import com.baosight.risk.mapper.ridc.RidcRiskMapper;
import com.baosight.risk.mapper.rifi.RifiEvaluateMapper;
import com.baosight.risk.mapper.rifi.RifiRiskFinishMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.rire.RireRiskWarningStatusMapper;
import com.baosight.risk.mapper.riri.RiriDutyUserMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringStatusMapper;
import com.baosight.risk.mapper.xtdc.XtdcAttachMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.riaa.entity.RiaaEvaluate;
import com.baosight.risk.service.ridc.entity.RidcRisk;
import com.baosight.risk.service.rifi.entity.RifiEvaluate;
import com.baosight.risk.service.rifi.entity.RifiRiskFinish;
import com.baosight.risk.service.rifi.vo.RifiEvaluateVO;
import com.baosight.risk.service.rifi.vo.RifiFinishVO;
import com.baosight.risk.service.riim.entity.RiimRiskGoal;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.riri.entity.RiriDutyUser;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringStatus;
import com.baosight.risk.service.system.entity.SysRole;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyRole;
import com.baosight.risk.service.xtzy.entity.XtzyRoleUser;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.xtzy.vo.XtzyUserVO;
import com.baosight.risk.web.freemarker.FreeMarkerController;
import com.baosight.risk.web.netty.SocketIO;
//import com.ibm.icu.impl.ICULocaleService;
//import com.ibm.icu.impl.duration.impl.DataRecord;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RifiRiskServiceImpl extends BaseServiceImpl<RifiRiskFinish> implements RifiRiskFinishService, UpdateHandler, AfterHandler {

    @Autowired
    private FreeMarkerController freeMarkerController;
    @Autowired
    private RifiRiskFinishService riskFinishService;
    @Autowired
    private RifiRiskFinishMapper rifiRiskFinishMapper;
    @Autowired
    private RifiEvaluateMapper rifiEvaluateMapper;
    @Autowired
    private RiaaEvaluateMapper riaaEvaluateMapper;
    @Autowired
    private RidcRiskMapper ridcRiskMapper;
    @Autowired
    private RiimRiskImportMapper riimRiskImportMapper;
    @Autowired
    private RiimRiskGoalMapper riimRiskGoalMapper;
    @Autowired
    private RiwaRiskWaringStatusMapper riwaRiskWaringStatusMapper;
    @Autowired
    private RiwaRiskWaringMapper riwaRiskWaringMapper;
    @Autowired
    private RireRiskWarningStatusMapper rireRiskWaringStatusMapper;
    @Autowired
    private XtdcAttachMapper xtdcAttachMapper;
    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    private RiriDutyUserMapper userMapper;
    @Autowired
    private XtzyCompanyMapper companyMapper;
    @Autowired
    private BaseRedis baseRedis;
    @Autowired
    private FltdTaskService fltdTaskService;
    @Autowired
    private SocketIO socketServer;
    @Autowired
    private FltdTaskMapper fltdTaskMapper;
    @Autowired
    private XtzyUserMapper xtzyUserMapper;
    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;
    @Autowired
    private IXtzyRoleUserService roleUserService;

    @Override
    public RifiEvaluateVO rifiEvaluate(RifiRiskFinish finish) {
        RifiRiskFinish rifiRiskFinish = rifiRiskFinishMapper.selectByPrimaryKey(finish.getId());
        RiimRiskImport riimRiskImport1 = riimRiskImportMapper.selectByPrimaryKey(rifiRiskFinish.getImportGuid());
        RifiEvaluateVO rifiEvaluateVO = new RifiEvaluateVO();
        List<RifiEvaluate> rifiEvaluates = rifiEvaluateMapper.selectList(finish);
        rifiEvaluateVO.setRiimRiskImport(riimRiskImport1);
        rifiEvaluateVO.setRifiRiskFinish(rifiRiskFinish);
        rifiEvaluateVO.setRifiEvaluateList(rifiEvaluates);
        return rifiEvaluateVO;

    }


    @Override
    public Integer saveRifiEvaluate(RifiEvaluateVO rifiEvaluateVO) {
        //保存结题信息
        RifiRiskFinish rifiRiskFinish = rifiEvaluateVO.getRifiRiskFinish();
        //保存能力测评
        List<RifiEvaluate> rifiEvaluateList = rifiEvaluateVO.getRifiEvaluateList();
        //领域值
        Map<String, BigDecimal> fieldValueMap = new HashMap<>();
        //领域占比
        Map<String, BigDecimal> fieldMap = new HashMap<>();
        //新的领域占比
        Map<String, BigDecimal> newFieldMap = new HashMap<>();
        //首先給各項测评结果赋值
        for (RifiEvaluate evaluate : rifiEvaluateList) {
            if ("1".equals(evaluate.getAssessCode())) {
                evaluate.setAssessValue(BigDecimal.valueOf(1));
            }
            if ("2".equals(evaluate.getAssessCode())) {
                evaluate.setAssessValue(BigDecimal.valueOf(0.8));
            }
            if ("3".equals(evaluate.getAssessCode())) {
                evaluate.setAssessValue(BigDecimal.valueOf(0.6));
            }
            if ("4".equals(evaluate.getAssessCode())) {
                evaluate.setAssessValue(BigDecimal.valueOf(0.4));
            }
            if ("5".equals(evaluate.getAssessCode())) {
                evaluate.setAssessValue(BigDecimal.valueOf(0.2));
            }
            if ("6".equals(evaluate.getAssessCode())) {
                evaluate.setAssessValue(BigDecimal.valueOf(0));
            }
            rifiEvaluateMapper.updateByPrimaryKeySelective(evaluate);
            fieldMap.put(evaluate.getFieldName(), evaluate.getWeight());
        }
        for (String fieldCode : fieldMap.keySet()) {
            int count = 0;//计算测评结果不是《不适用》的数量
            BigDecimal sum = new BigDecimal(0);
            for (RifiEvaluate evaluate : rifiEvaluateList) {
                if (fieldCode.equals(evaluate.getFieldName()) && !"6".equals(evaluate.getAssessCode())) {
                    //计算每项领域不适用的数量
                    count++;
                    sum = sum.add(evaluate.getAssessValue());
                }
            }
            if (count != 0) {
                newFieldMap.put(fieldCode, fieldMap.get(fieldCode));
                fieldValueMap.put(fieldCode, sum.divide(new BigDecimal(count), 10, BigDecimal.ROUND_HALF_UP));//保留兩位小数
            }
        }
//        计算新的比例
        BigDecimal newSum = new BigDecimal("0");
        for (String s : newFieldMap.keySet()) {
            BigDecimal bigDecimal = fieldMap.get(s);
            newSum = newSum.add(bigDecimal);
        }
        for (String s : newFieldMap.keySet()) {
            BigDecimal bigDecimal = newFieldMap.get(s);
            newFieldMap.put(s, bigDecimal.divide(newSum, 10, BigDecimal.ROUND_HALF_UP));
        }
        //計算最終結果
        BigDecimal finalSum = new BigDecimal("0");
        for (String s : newFieldMap.keySet()) {
            BigDecimal bigDecimal = newFieldMap.get(s);
            for (String s1 : fieldValueMap.keySet()) {
                if (s.equals(s1)) {
                    finalSum = finalSum.add(bigDecimal.multiply(fieldValueMap.get(s1)));
                }
            }
        }
        BigDecimal multiply = finalSum.multiply(new BigDecimal("100"));
        rifiRiskFinish.setAssessValue(multiply);
        rifiRiskFinishMapper.updateByPrimaryKeySelective(rifiRiskFinish);
        return 1;
    }


    @Override
    public Integer saveRifiFinish(RifiFinishVO rifiFinishVO) {
        boolean lock = baseRedis.louck("lock");
        if (lock) {
            //获取结题申请数据
            RiimRiskImport riimRiskImport1 = rifiFinishVO.getRiimRiskImport();
            riimRiskImport1 = (RiimRiskImport) BeanUtils.updateBean(riimRiskImport1);
            riimRiskImportMapper.updateByPrimaryKeySelective(riimRiskImport1);
            //获取结题数据
            RifiRiskFinish rifiRiskFinish = rifiFinishVO.getRifiRiskFinish();
            //查看数据库是否已经存在结题数据，存在则更新,不存在则新增
            RifiRiskFinish rifiRiskFinish1 = rifiRiskFinishMapper.selectByImportGuid(riimRiskImport1.getId());
            if (rifiRiskFinish1 == null) {
                BeanUtils.copyBeanProp(rifiRiskFinish, riimRiskImport1);
                rifiRiskFinish = (RifiRiskFinish) BeanUtils.initBean(rifiRiskFinish);
                rifiRiskFinish.setEditDate(new Date());
                rifiRiskFinish.setIsFinish(0);
                rifiRiskFinish.setAssessResult(null);
                rifiRiskFinish.setTeamAdvice(null);
                rifiRiskFinish.setAssessValue(null);
                rifiRiskFinish.setDeptAdvice(null);
                rifiRiskFinish.setDeptAdviceDate(null);
                rifiRiskFinish.setDeptLeadName(null);
                rifiRiskFinish.setAssessLeadName(null);
                rifiRiskFinish.setAssessAdviceDate(null);
                rifiRiskFinish.setAssessLeadAdvice(null);
                rifiRiskFinishMapper.insert(rifiRiskFinish);
            } else {
                rifiRiskFinish = (RifiRiskFinish) BeanUtils.updateBean(rifiRiskFinish);
                rifiRiskFinishMapper.updateByPrimaryKeySelective(rifiRiskFinish);
            }
            //更新实施方案状态
            List<RiimRiskGoal> riimRiskGoals = rifiFinishVO.getRiimRiskGoals();
            if (CollectionUtils.isNotEmpty(riimRiskGoals)) {
                for (RiimRiskGoal rg : riimRiskGoals) {
                    riimRiskGoalMapper.updateByPrimaryKeySelective(rg);
                }
            }
            baseRedis.unLouck("lock");
            return 1;
        } else {
            return 0;
        }

    }

    @Override
    public List<RiimRiskImport> selectList(RiimRiskImportVO riimRiskImport) {
        ArrayList<RiimRiskImport> riimIportsRidc = new ArrayList<>();
        ArrayList<RiimRiskImport> riimIportsReport = new ArrayList<>();
        ArrayList<RiimRiskImport> riimIportsReport2 = new ArrayList<>();
        XtzyUser user = ShiroUtils.getUser();
        String userCode = user.getUserCode();
       /* String acctYear = DateUtils.format(new Date(), "yyyy");
        acctYear=Integer.parseInt(acctYear)-1+"";*/
        //条件查询是否下发
        if ("Y".equals(riimRiskImport.getConclusionStatus())){
            riimRiskImport.setConclusionStatus("Y");
        }else if ("N".equals(riimRiskImport.getConclusionStatus())){
            riimRiskImport.setConclusionStatus("未下发");
        }

        String quarterReport = DateUtils.getQuarter(new Date());
        if (user.isAdmin()) {
            List<RiimRiskImport> riimImports = riimRiskImportMapper.selectListByFinish(riimRiskImport);
            for (RiimRiskImport riskImport:riimImports){
                if ("Y".equals(riskImport.getConclusionStatus())){
                    riskImport.setConclusionStatus("已下发");
                }else {
                    riskImport.setConclusionStatus("未下发");
                }
            }
            return riimImports;
        }
    //   riimRiskImport.setDutyUserCode(userCode);
   //     riimRiskImport.setFinishStatus("A01");
//        List<RiimRiskImport> riimImports = riimRiskImportMapper.selectListByFinish(riimRiskImport);
//        return riimImports;


        //筛选数据 如果当前登陆人的角色为 ——  则查询当前机构的全部 否则赛选出数据责任人为当前登陆人
        //获取当前登陆人所在公司下的所有角色

        List<XtzyUserVO> xtzyUserVOS = roleUserService.queryUserRole(user.getExt1(), "", user.getUserCode());
        if(xtzyUserVOS.size()>0){
            List<XtzyRoleUser> rolesByUserCode = xtzyUserVOS.get(0).getRoleuserList();
            rolesByUserCode = rolesByUserCode.stream().filter(res -> res.getRoleName().equals("风险部门风险管理员")).collect(Collectors.toList());
            //如果不是风险部门风险管理 则只查询当前登陆人所在的责任人员
            if (CollectionUtils.isEmpty(rolesByUserCode) || rolesByUserCode.size() == 0) {
                riimRiskImport.setDutyUserCode(userCode);
                //riimImports = riimImports.stream().filter(res -> res.getDutyUserCode().equals(userCode)).collect(Collectors.toList());
            }
            if (rolesByUserCode.size()>0){
                //如果是风险管理员不等于查询条件的基地 则按照责任人查询
                String orgCode=rolesByUserCode.get(0).getRoleCompCode();
                if (riimRiskImport.getManageCompCode()!=null){
                    if (!orgCode.equals(riimRiskImport.getManageCompCode())){
                        riimRiskImport.setDutyUserCode(userCode);
                    }
                }

            }
        }

        //1、取出当前登陆人负责的状态A01的重点风险riimImports
        List<RiimRiskImport> riimImports = riimRiskImportMapper.selectListByFinish(riimRiskImport);

        for (RiimRiskImport riskImport:riimImports){
            if ("Y".equals(riskImport.getConclusionStatus())){
                riskImport.setConclusionStatus("已下发");
            }else {
                riskImport.setConclusionStatus("未下发");
            }
        }

        return riimImports;
        //2、找到有风险档案的重点风险:riimIportsRidc
//        riimImports.forEach(n -> {
//            RidcRisk ridcRiskQ = new RidcRisk();
//            ridcRiskQ.setAcctYear(n.getAcctYear());
//            ridcRiskQ.setRiskNo(n.getRiskNo());
//            RidcRisk ridcRisk = ridcRiskMapper.selectOne(ridcRiskQ);
//            if (ridcRisk != null) {
//                riimIportsRidc.add(n);
//            }
//        });
//        //3、找到连续四个季度有披露报告的重点风险:riimIportsReport
//        for (RiimRiskImport rri : riimIportsRidc) {
//            String acctYear = rri.getAcctYear();
//            Integer quarterInt = Integer.valueOf(quarterReport);
//            String lastYear = String.valueOf(Integer.valueOf(acctYear) - 1);
//            int count = 0;//计算披露报告的数量
//            if ("4".equals(quarterReport)) {
//                for (int j = 4; j >= 1; j--) {
//                    RireRiskWarningStatus riwaRiskWaringStatus = getRireRiskWarningStatus(rri, acctYear, j);
//                    if (riwaRiskWaringStatus != null) {
//                        count++;
//                    }
//                }
//            } else {
//                //找到当前重点风险的上一年的重点风险
//                RiimRiskImport riskImportQ = new RiimRiskImport();
//                riskImportQ.setAcctYear(lastYear);
//                riskImportQ.setHisRiskId(rri.getHisRiskId());
//                RiimRiskImport riskImportLast = riimRiskImportMapper.selectOne(riskImportQ);
//                if (riskImportLast != null) {
//                    for (int h = quarterInt; h >= 1; h--) {
//                        RireRiskWarningStatus rireRiskWaringStatus = getRireRiskWarningStatus(rri, acctYear, h);
//                        if (rireRiskWaringStatus != null) {
//                            count++;
//                        }
//                    }
//                    for (int i = 4; i > quarterInt; i--) {
//                        RireRiskWarningStatus rireRiskWaringStatus = getRireRiskWarningStatus(riskImportLast, lastYear, i);
//                        if (rireRiskWaringStatus != null) {
//                            count++;
//                        }
//                    }
//                }
//            }
//            if (count == 4) {
//                riimIportsReport.add(rri);
//            }
//        }
//        //4、找出连续三个季度披露报告非红黑灯的重点风险riimIportsReport2
//        for (RiimRiskImport rir : riimIportsReport) {
//            String acctYear = rir.getAcctYear();
//            Integer quarterInt = Integer.valueOf(quarterReport);
//            String lastYear = String.valueOf(Integer.valueOf(acctYear) - 1);
//            int count = 0;//计算披露报告的数量
//            if ("4".equals(quarterReport) || "3".equals(quarterReport)) {
//                for (int j = quarterInt; j >= quarterInt - 2; j--) {
//                    RireRiskWarningStatus riwaRiskWaringStatus = getRireRiskWarningStatus(rir, acctYear, j);
//                    if (!"red".equals(riwaRiskWaringStatus) && !"black".equals(riwaRiskWaringStatus)) {
//                        count++;
//                    }
//                }
//            } else {
//                //找到当前重点风险的上一年的重点风险
//                RiimRiskImport riskImportQ = new RiimRiskImport();
//                riskImportQ.setAcctYear(lastYear);
//                riskImportQ.setHisRiskId(rir.getHisRiskId());
//                RiimRiskImport riskImportLast = riimRiskImportMapper.selectOne(riskImportQ);
//                if (riskImportLast != null) {
//                    for (int h = quarterInt; h > 0; h--) {
//                        RireRiskWarningStatus riwaRiskWaringStatus = getRireRiskWarningStatus(rir, acctYear, h);
//                        if (!"red".equals(riwaRiskWaringStatus) && !"black".equals(riwaRiskWaringStatus)) {
//                            count++;
//                        }
//                    }
//                    for (int i = 4; i > quarterInt + 1; i--) {
//                        RireRiskWarningStatus riwaRiskWaringStatus = getRireRiskWarningStatus(riskImportLast, lastYear, i);
//                        if (!"red".equals(riwaRiskWaringStatus) && !"black".equals(riwaRiskWaringStatus)) {
//                            count++;
//                        }
//                    }
//                }
//            }
//            if (count == 3) {
//                riimIportsReport2.add(rir);
//            }
//        }
//        return riimIportsReport2;
    }

    /**
     * @param rir      披露报告
     * @param acctYear 年度
     * @param h        季度
     * @return
     */
    //获取披露报告方法
    private RireRiskWarningStatus getRireRiskWarningStatus(RiimRiskImport rir, String acctYear, int h) {
        RireRiskWarningStatus rireRiskWarningStatusQ = new RireRiskWarningStatus();
        rireRiskWarningStatusQ.setImportGuid(rir.getId());
        rireRiskWarningStatusQ.setAcctYear(acctYear);
        rireRiskWarningStatusQ.setQuarterCode(String.valueOf(h));
        return rireRiskWaringStatusMapper.selectOne(rireRiskWarningStatusQ);
    }

    /**
     * 获取结题申请页面数据
     */
    @Override
    public RifiFinishVO getFinishByImportId(RiimRiskImport riimRiskImport) {
        //重点风险数据
        RifiFinishVO rifiFinishVO = new RifiFinishVO();
        //由于风险结题页面下发时获取风险结题申请,通过传过来的RiimRiskImport无查询结果,所以在此换持久层就扣方法
        //RiimRiskImport riimRiskImport1 = riimRiskImportMapper.selectOne(riimRiskImport);
        //RiimRiskImport riimRiskImport1 = riimRiskImportMapper.selectByRiskIdAndYearAndRiskNo(riimRiskImport);
        RiimRiskImport riimRiskImport1 = riimRiskImportMapper.selectById(riimRiskImport);
        //风险结题数据
        RifiRiskFinish rifiRiskFinish = new RifiRiskFinish();
        rifiRiskFinish.setImportGuid(riimRiskImport.getId());
        rifiRiskFinish.setIsFinish(0);//正常流程
        RifiRiskFinish rifiRiskFinish1 = rifiRiskFinishMapper.selectLastedOne(rifiRiskFinish);
        if (rifiRiskFinish1 == null) {
            RifiRiskFinish finishOverQ = new RifiRiskFinish();
            finishOverQ.setImportGuid(riimRiskImport.getId());
            finishOverQ.setIsFinish(1);//上一条非正常关闭流程
            RifiRiskFinish finishOver = rifiRiskFinishMapper.selectLastedOne(finishOverQ);
            if (finishOver == null) {
                RifiRiskFinish finish = (RifiRiskFinish) BeanUtils.initBean(rifiRiskFinish);
                rifiFinishVO.setRifiRiskFinish(finish);
            } else {
                rifiFinishVO.setRifiRiskFinish(finishOver);
            }
        } else {
            rifiFinishVO.setRifiRiskFinish(rifiRiskFinish1);
        }
        //重点风险实施方案数据
        RiimRiskGoal riimRiskGoal = new RiimRiskGoal();
        riimRiskGoal.setImportGuid(riimRiskImport.getId());
        List<RiimRiskGoal> riimRiskGoals = riimRiskGoalMapper.select(riimRiskGoal);
        //风险档案数据
        RidcRisk ridcRisk = new RidcRisk();
        ridcRisk.setRiskNo(riimRiskImport1.getRiskNo());
        ridcRisk.setAcctYear(riimRiskImport1.getAcctYear());
        ridcRisk.setManageCompCode(riimRiskImport1.getManageCompCode());
        RidcRisk ridcRisk1 = ridcRiskMapper.selectOne(ridcRisk);
        rifiFinishVO.setRidcRisk(ridcRisk1);
        rifiFinishVO.setRiimRiskImport(riimRiskImport1);
        rifiFinishVO.setRiimRiskGoals(riimRiskGoals);
        //根据业务id查找文件名称===附件展示
        List<RifiFinishVO.File> fileList = new ArrayList<RifiFinishVO.File>();
        List<XtdcAttach> xtdcAttaches = xtdcAttachMapper.selectBySourceGuid(riimRiskImport.getId());
        if (CollectionUtils.isNotEmpty(xtdcAttaches)) {
            for (XtdcAttach x : xtdcAttaches
            ) {
                RifiFinishVO.File file = rifiFinishVO.new File();
                file.setUrl(null);
                file.setName(StringUtils.substringAfterLast(x.getFileName(), "_"));
                fileList.add(file);
            }
        }
        rifiFinishVO.setFileList(fileList);
        return rifiFinishVO;
    }

    /**
     * 获取评审小组人员发待办
     *
     * @param params
     * @return
     */
    public List<XtzyUser> getUser(Map<String, String> params) {

        String bizGuid = params.get("bizGuid");
        String taskGuid = params.get("taskGuid");
        String bizType = params.get("bizType");
        String yyyy = DateUtils.format(new Date(), "yyyy");
        //拼装查询条件找出风险档案推进人
        RiriDutyUser ririDutyUser = new RiriDutyUser();
        ririDutyUser.setBizType(bizType);
        ririDutyUser.setBizGuid(bizGuid);
        ririDutyUser.setExt1(taskGuid);
        List<RiriDutyUser> userList = userMapper.select(ririDutyUser);
        //提交推进人给工作流
        List<XtzyUser> xtzyUsers = new ArrayList<>();
        for (RiriDutyUser user : userList) {
            XtzyUser xtzyUser = new XtzyUser();
            xtzyUser.setUserCode(user.getUserCode());
            xtzyUser.setUserDesc(user.getUserDesc());
            xtzyUser.setExt1(user.getCompCode());
            xtzyUser.setExt2(user.getCompName());
            xtzyUsers.add(xtzyUser);
        }
        return xtzyUsers;
    }

    //下发能力测评
    @Override
    public void doIssuedEvaluate(RifiRiskFinish finish) {
        //找出最新關閉的一条已结题记录
        List<RifiEvaluate> select = null;
        RifiRiskFinish finishQ = new RifiRiskFinish();
        finishQ.setImportGuid(finish.getImportGuid());
        finishQ.setIsFinish(1);
        RifiRiskFinish finishLast = rifiRiskFinishMapper.selectLastedOne(finishQ);
        if (finishLast != null) {
            //如果上一条结题数据没有，下发测评数据。如果有，进入下一步判断
            RifiEvaluate evaluateQ = new RifiEvaluate();
            evaluateQ.setImportId(finish.getImportGuid());
            evaluateQ.setFinishId(finishLast.getId());
            select = rifiEvaluateMapper.select(evaluateQ);
        }
        if (CollectionUtils.isNotEmpty(select)) { //如果上一条关闭的结题数据存在，直接代入进新的结题测评数据
            select.forEach(n -> {
                n = (RifiEvaluate) BeanUtils.initBean(n);
                n.setFinishId(finish.getId());
                n.setImportId(finish.getImportGuid());
                rifiEvaluateMapper.insert(n);
            });
        }
        //如果不存在，重新下发
        else {
            List<RiaaEvaluate> evaluateList = riaaEvaluateMapper.selectFieldList(new RiaaEvaluate());
            for (RiaaEvaluate riaaEvaluate : evaluateList) {
                //新增测评标准
                List<RiaaEvaluate> list = riaaEvaluateMapper.selectDetailList(riaaEvaluate.getId());
                if (CollectionUtils.isNotEmpty(list)) {
                    for (RiaaEvaluate evaluate : list) {
                        RifiEvaluate rifiEvaluate2 = new RifiEvaluate();
                        BeanUtils.copyBeanProp(rifiEvaluate2, evaluate);
                        rifiEvaluate2.setWeight(riaaEvaluate.getWeight());
                        rifiEvaluate2.setFieldCode(riaaEvaluate.getFieldCode());
                        rifiEvaluate2.setFieldName(riaaEvaluate.getFieldName());
                        rifiEvaluate2.setEvaluateNo(riaaEvaluate.getEvaluateNo());
                        rifiEvaluate2.setManageTarget(riaaEvaluate.getManageTarget());
                        rifiEvaluate2.setImportId(finish.getImportGuid());
                        rifiEvaluate2.setFinishId(finish.getId());
                        rifiEvaluate2 = (RifiEvaluate) BeanUtils.initBean(rifiEvaluate2);
                        rifiEvaluateMapper.insert(rifiEvaluate2);
                    }
                }
            }
        }
    }

    @Override
    public List<RifiRiskFinish> selectOverList(RifiRiskFinish riskFinish) {
        //结题信息查询条件
        XtzyUser user = ShiroUtils.getUser();
        if (!user.isAdmin()) {
            riskFinish.setCreateBy(user.getUserCode());
        }
        List<RifiRiskFinish> select = rifiRiskFinishMapper.selectList(riskFinish);
        return select;
    }

    @Override
    public RifiFinishVO getRifiFinishOver(RifiRiskFinish finish) {
        //重点风险数据
        RifiFinishVO rifiFinishVO = new RifiFinishVO();
        RiimRiskImport riimRiskImport1 = riimRiskImportMapper.selectByPrimaryKey(finish.getImportGuid());
        //风险结题数据

        RifiRiskFinish rifiRiskFinish = new RifiRiskFinish();
        rifiRiskFinish.setId(finish.getId());
        rifiRiskFinish.setImportGuid(finish.getImportGuid());
        RifiRiskFinish rifiRiskFinish1 = rifiRiskFinishMapper.selectOne(rifiRiskFinish);
        rifiFinishVO.setRifiRiskFinish(rifiRiskFinish1);
        //重点风险实施方案数据
        RiimRiskGoal riimRiskGoal = new RiimRiskGoal();
        riimRiskGoal.setImportGuid(riimRiskImport1.getId());
        List<RiimRiskGoal> riimRiskGoals = riimRiskGoalMapper.select(riimRiskGoal);
        //风险档案数据
        RidcRisk ridcRisk = new RidcRisk();
        ridcRisk.setRiskNo(riimRiskImport1.getRiskNo());
        ridcRisk.setAcctYear(riimRiskImport1.getAcctYear());
        RidcRisk ridcRisk1 = ridcRiskMapper.selectOne(ridcRisk);
        rifiFinishVO.setRidcRisk(ridcRisk1);
        rifiFinishVO.setRiimRiskImport(riimRiskImport1);
        rifiFinishVO.setRiimRiskGoals(riimRiskGoals);
        //根据业务id查找文件名称===附件展示
        List<RifiFinishVO.File> fileList = new ArrayList<RifiFinishVO.File>();
        List<XtdcAttach> xtdcAttaches = xtdcAttachMapper.selectBySourceGuid(finish.getImportGuid());
        if (CollectionUtils.isNotEmpty(xtdcAttaches)) {
            for (XtdcAttach x : xtdcAttaches
            ) {
                RifiFinishVO.File file = rifiFinishVO.new File();
                file.setUrl(null);
                file.setName(StringUtils.substringAfterLast(x.getFileName(), "_"));
                fileList.add(file);
            }
        }
        rifiFinishVO.setFileList(fileList);
        return rifiFinishVO;
    }

    @Override
    public Map importWordList(List<String> importIds) {
        Map map = new HashMap<String, Object>();
        int index = 0;
        List<Map> list = new ArrayList<>();
        for (String importId : importIds) {
            Map map1 = importWord(importId);
            map1.put("size", index += 1);
            list.add(map1);
        }
        map.put("mainlist", list);
        return map;





    }

    @Override
    public List<FltdTask> selectListByIds(String[] ids) {
        ArrayList<FltdTask> fltdTasks = new ArrayList<>();
        for (String id:ids){
            RiimRiskImport riskImport = riimRiskImportMapper.selectByPrimaryKey(id);
            FltdTask fltdTask = new FltdTask();
            fltdTask.setCurrUserCode(riskImport.getDutyUserCode());
            fltdTask.setCurrUserName(riskImport.getDutyUserName());
            fltdTasks.add(fltdTask);
        }
        return fltdTasks;
    }

    @Override
    public void doSubmit(RiimRiskImport riimRiskImport) throws Exception {//风险结题doSubmit
        Exception error = null;
        try {
            RiimRiskImport riimImport1 = riimRiskImportMapper.selectByPrimaryKey(riimRiskImport.getId());
            RifiRiskFinish finish = rifiRiskFinishMapper.selectByImportGuid(riimRiskImport.getId());
            FltdTaskVO taskVO = new FltdTaskVO();
            if("BGTA".equals(riimImport1.getManageCompCode())){
                taskVO.setFlowNo("fengxianjieti");
                taskVO.setFlowName("重点风险结题");
                taskVO.setBizName("重点风险结题");
                taskVO.setBizDesc("重点风险结题");
            }else{
                taskVO.setFlowNo("jidijieticeping");
                taskVO.setFlowName("基地重点风险结题");
                taskVO.setBizName("基地重点风险结题");
                taskVO.setBizDesc("基地重点风险结题");
            }

            taskVO.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            taskVO.setQuarterCode(DateUtils.getQuarter(new Date()));
            taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
            XtzyCompany company = new XtzyCompany();
            company.setCompCode(riimImport1.getDeptCode());
            company.setCompName(riimImport1.getDeptName());
            taskVO.setCustomCompany(company);
            taskVO.setCompCode(riimImport1.getCompCode());
            taskVO.setCompName(riimImport1.getCompName());
            taskVO.setDeptCode(riimImport1.getDeptCode());
            taskVO.setDeptName(riimImport1.getDeptName());
            taskVO.setBizName(riimImport1.getRiskName());
            taskVO.setManageCompCode(riimImport1.getManageCompCode());
            taskVO.setManageCompName(riimImport1.getManageCompName());
            String bizDesc = "<" + riimImport1.getRiskName() + ">" + "重点风险结题";
            taskVO.setBizDesc(bizDesc);
            taskVO.setBizGuid(finish.getId());
            taskVO.setTaskGuid(riimImport1.getId());
            taskVO.setGroupCondition(taskVO.getAcctYear() + taskVO.getQuarterCode());
            try {
                fltdProcessService.doStart(taskVO);
                // 保存日志到数据库
                AsyncManager.me().execute(AsyncFactory.recordOper(
                        fltdProcessService.getLog("重点风险结题-流程启动成功", 0, "业务id：" + riimImport1.getId() + "，重点风险id：" + riimImport1.getId(), null)));
            } catch (Exception e) {
                // 保存日志到数据库
                AsyncManager.me().execute(AsyncFactory.recordOper(
                        fltdProcessService.getLog("重点风险结题-流程启动失败", 1, "业务id：" + riimImport1.getId() + "，重点风险id：" + riimImport1.getId() + ", 失败原因：" + e.getMessage(), null)));
                error = e;
            }
        } catch (Exception e) {
            // 保存日志到数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(
                    fltdProcessService.getLog("重点风险结题-下发异常", 1, e.getMessage(), null)));
            error = e;
        }
        if (error != null) {
            throw error;
        }
    }


    @Override
    public Map importWord(String importId) {
        Map map = new HashMap<String, Object>();
        RiimRiskImport riimRiskImport = riimRiskImportMapper.selectByPrimaryKey(importId);
        RifiRiskFinish rifiRiskFinish = new RifiRiskFinish();
        rifiRiskFinish.setImportGuid(riimRiskImport.getId());
        RifiRiskFinish rifi = rifiRiskFinishMapper.selectByImportGuid(riimRiskImport.getId());
        RidcRisk ridcRisk = new RidcRisk();
        ridcRisk.setRiskNo(riimRiskImport.getRiskNo());
        ridcRisk.setAcctYear(riimRiskImport.getAcctYear());
        ridcRisk.setManageCompCode(riimRiskImport.getManageCompCode());
        RidcRisk ridcRisk1 = ridcRiskMapper.selectOne(ridcRisk);
        String auditFormat = "";
        String planBeginFormat = "";
        String planEndFormat = "";
        String deptAdviceFormat = "";
        String editFormat = "";
        String assessFormat = "";
        if (riimRiskImport != null) {
            auditFormat = DateUtils.format(riimRiskImport.getAuditDate(), "yyyy-MM-dd");
            planBeginFormat = DateUtils.format(riimRiskImport.getFactBeginDate(), "yyyy-MM-dd");
            planEndFormat = DateUtils.format(riimRiskImport.getFactEndDate(), "yyyy-MM-dd");
            map.put("riskName", StringUtils.isEmpty(riimRiskImport.getRiskName()) ? " " : zhaunhuan(riimRiskImport.getRiskName()));
            map.put("compName", StringUtils.isEmpty(riimRiskImport.getCompName()) ? " " : zhaunhuan(riimRiskImport.getCompName()));
            map.put("dutyUserName", StringUtils.isEmpty(riimRiskImport.getDutyUserName()) ? " " : zhaunhuan(riimRiskImport.getDutyUserName()));
            map.put("phone", StringUtils.isEmpty(riimRiskImport.getTelephone()) ? " " : zhaunhuan(riimRiskImport.getTelephone()));
        } else {
            map.put("riskName", " ");
            map.put("compName", " ");
            map.put("dutyLeadName", " ");
            map.put("phone", " ");
        }
        if (rifi != null) {
            if (!"A01".equals(rifi.getFinishStatus())) {
                deptAdviceFormat = DateUtils.format(rifi.getDeptAdviceDate(), "yyyy-MM-dd");
            }
            editFormat = DateUtils.format(rifi.getEditDate(), "yyyy-MM-dd");
            assessFormat = DateUtils.format(rifi.getAssessAdviceDate(), "yyyy-MM-dd");
            map.put("finishLeadName", StringUtils.isEmpty(rifi.getDeptLeadName()) ? " " : zhaunhuan(rifi.getDeptLeadName()));
            map.put("finishDesc", StringUtils.isEmpty(rifi.getFinishDesc()) ? " " : zhaunhuan(rifi.getFinishDesc()));
            map.put("institution", StringUtils.isEmpty(rifi.getInstitution()) ? " " : zhaunhuan(rifi.getInstitution()));
            map.put("riskDesc", StringUtils.isEmpty(riimRiskImport.getRiskDesc()) ? " " : zhaunhuan(riimRiskImport.getRiskDesc()));
            map.put("deptAdvice", StringUtils.isEmpty(rifi.getDeptAdvice()) ? " " : zhaunhuan(rifi.getDeptAdvice()));
            map.put("assessDesc", rifi.getAssessValue() == null ? " " : zhaunhuan(rifi.getAssessValue() + ""));
            map.put("assessResult", StringUtils.isEmpty(rifi.getAssessResult()) ? " " : zhaunhuan(rifi.getAssessResult()));
            map.put("teamAdvice", StringUtils.isEmpty(rifi.getTeamAdvice()) ? " " : zhaunhuan(rifi.getTeamAdvice()));
            map.put("assessLeadAdvice", StringUtils.isEmpty(rifi.getAssessLeadAdvice()) ? " " : zhaunhuan(rifi.getAssessLeadAdvice()));
            map.put("assessLeadName", StringUtils.isEmpty(rifi.getAssessLeadName()) ? " " : zhaunhuan(rifi.getAssessLeadName()));
        } else {
            map.put("finishLeadName", " ");
            map.put("finishDesc", " ");
            map.put("institution", " ");
            map.put("riskDesc", " ");
            map.put("deptAdvice", " ");
            map.put("assessDesc", " ");
            map.put("assessResult", " ");
            map.put("teamAdvice", " ");
            map.put("assessLeadAdvice", " ");
            map.put("assessLeadName", " ");
        }

        map.put("createDate", StringUtils.isEmpty(auditFormat) ? " " : zhaunhuan(auditFormat));
        map.put("planBeginDate", StringUtils.isEmpty(planBeginFormat) ? " " : zhaunhuan(planBeginFormat));
        map.put("planEndDate", StringUtils.isEmpty(planEndFormat) ? " " : zhaunhuan(planEndFormat));
        map.put("editDate", StringUtils.isEmpty(editFormat) ? " " : zhaunhuan(editFormat));
        map.put("deptAdviceDate", StringUtils.isEmpty(deptAdviceFormat) ? " " : zhaunhuan(deptAdviceFormat));
        map.put("reportName", ridcRisk1 == null ? " " : zhaunhuan(ridcRisk1.getAcctYear() + "年度<" + ridcRisk1.getRiskName() + ">风险档案"));//暂留
        map.put("assessAdviceDate", StringUtils.isEmpty(assessFormat) ? " " : zhaunhuan(assessFormat));

        List<Map<String, Object>> list = new ArrayList<>();
        List<RiaaEvaluate> riaaEvaluates = riaaEvaluateMapper.selectFieldList(new RiaaEvaluate());
        int indexF = 0;
        if (CollectionUtils.isNotEmpty(riaaEvaluates)) {
            for (RiaaEvaluate riaaF : riaaEvaluates) {
                Map<String, Object> mapF = new HashMap<>();
                mapF.put("index", ++indexF);
                mapF.put("fieldName", zhaunhuan(riaaF.getFieldName()));
                mapF.put("manageTarget", zhaunhuan(riaaF.getManageTarget()));
                List<Map<String, Object>> listS = new ArrayList<>();
                List<RiaaEvaluate> riaaEvaluatesF = riaaEvaluateMapper.selectDetailList(riaaF.getId());
                int indexS = 0;
                if (CollectionUtils.isNotEmpty(riaaEvaluatesF)) {
                    for (RiaaEvaluate riaaS : riaaEvaluatesF) {
                        Map<String, Object> mapS = new HashMap<>();
                        mapS.put("index", ++indexS);
                        mapS.put("assessStandard", zhaunhuan(riaaS.getAssessStandard()));
                        listS.add(mapS);
                    }
                } else {
                    Map<String, Object> mapS = new HashMap<>();
                    mapS.put("index", " ");
                    mapS.put("assessStandard", " ");
                }
                mapF.put("listA", listS);
                list.add(mapF);
            }
        } else {
            List<Map<String, Object>> listS = new ArrayList<>();
            Map<String, Object> mapS = new HashMap<>();
            mapS.put("index", " ");
            mapS.put("assessStandard", " ");
            listS.add(mapS);
            Map<String, Object> mapF = new HashMap<>();
            mapF.put("index", " ");
            mapF.put("fieldName", " ");
            mapF.put("manageTarget", " ");
            mapF.put("listA", listS);
            list.add(mapF);
        }
        map.put("list", list);
        return map;
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     */
    @Override
    public boolean updateStatus(Map<String, Object> params) {
        try {
            String status = params.get("status").toString();
            String nextStatus = params.get("nextStatus").toString();
            String nextStatusName = params.get("nextStatusName").toString();
            String taskGuid = params.get("taskGuid").toString();
            //审批意见
            XtzyUser user = ShiroUtils.getUser();
            Object context = params.get("context");
            String contextStr = "";
            if (context != null) {
                contextStr = context.toString();
            }
            //更新状态
            RiimRiskImport riskImportQ = new RiimRiskImport();
            riskImportQ.setFinishStatus(nextStatus);
            riskImportQ.setFinishStatusName(nextStatusName);
            riskImportQ.setId(taskGuid);
            riskImportQ.setFinishReturn(0);
            //找出对应的rifi
            RifiRiskFinish rifiRiskFinish = new RifiRiskFinish();
            rifiRiskFinish.setImportGuid(taskGuid);
            rifiRiskFinish.setIsFinish(0);
            RifiRiskFinish rifi = rifiRiskFinishMapper.selectOne(rifiRiskFinish);
            rifi.setFinishStatus(nextStatus);
            rifi.setFinishStatusName(nextStatusName);
            updateWord(params);
            //判断审核时状态，根据状态更新对应参数
            if ("A01".equals(nextStatus)) {
                rifi.setDeptAdvice(" ");
                rifi.setDeptAdviceDate(null);
                rifi.setFinishLeadCode(" ");
                rifi.setDeptLeadName(" ");
                rifi.setAssessResult(" ");
                rifi.setTeamAdvice(" ");
                rifi.setTeamAdviceDate(null);
                rifi.setAssessLeadAdvice(" ");
                rifi.setAssessLeadName(" ");
                rifi.setAssessAdviceDate(null);
                rifiRiskFinishMapper.updateByPrimaryKey(rifi);
                riskImportQ.setFinishReturn(1);

            }
            //测评流程退回
            if ("B01".equals(nextStatus)) {
                rifi.setAssessResult(" ");
                rifi.setTeamAdvice(" ");
                rifi.setTeamAdviceDate(null);
                rifi.setAssessLeadAdvice(" ");
                rifi.setAssessLeadName(" ");
                rifi.setAssessAdviceDate(null);

            }
            //部门领导提交
            if ("A03".equals(nextStatus)) {
                rifi.setDeptAdvice(contextStr);
                rifi.setDeptAdviceDate(new Date());
                rifi.setFinishLeadCode(user.getUserCode());
                rifi.setDeptLeadName(user.getUserDesc());
            }
            //评审专家意见--暂时保留
            if ("B04".equals(status)) {
                RiriDutyUser dutyUserQ = new RiriDutyUser();
                dutyUserQ.setUserCode(user.getUserCode());
                dutyUserQ.setBizGuid(rifi.getId());
                rifi.setTeamAdvice(contextStr);
                rifi.setTeamAdviceDate(new Date());

            }
            //运改部最终结论
            if ("B05".equals(status)) {
                rifi.setTeamAdviceDate(new Date());
                rifi.setAssessLeadAdvice(contextStr);
                rifi.setAssessLeadName(ShiroUtils.getUser().getUserDesc());
                rifi.setAssessAdviceDate(new Date());
            }
            //结题完成，关闭该重点风险的风险档案
            if ("B07".equals(status)) {
                rifi.setAssessLeadAdvice(contextStr);
                rifi.setAssessLeadName(ShiroUtils.getUser().getUserDesc());
                rifi.setAssessAdviceDate(new Date());
//            RiimRiskImport riskImport = riimRiskImportMapper.selectByPrimaryKey(taskGuid);
            }
            //更新重点风险状态
            riimRiskImportMapper.updateByPrimaryKeySelective(riskImportQ);
            if (rifiRiskFinishMapper.updateByPrimaryKeySelective(rifi) > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean doAfter(Map<String, Object> params) {
        //后置处理参数
        String taskGuid = params.get("taskGuid").toString();
        RiimRiskImport riimImport1 = riimRiskImportMapper.selectByPrimaryKey(taskGuid);
        RifiRiskFinish finish = rifiRiskFinishMapper.selectByImportGuid(riimImport1.getId());
        updateWord(params);
        if (!"end".equals(params.get("submitType"))) {
            return true;
        } else if ("end".equals(params.get("submitType")) && "A01".equals(params.get("status"))) {
            finish.setIsFinish(1);
            finish.setFinishStatusName("已关闭");
            RiimRiskImport riskImportQ = new RiimRiskImport();
            BeanUtils.copyBeanProp(riskImportQ, riimImport1);
            riskImportQ.setFinishStatus("A01");
            riskImportQ.setFinishStatusName("草稿");
            riskImportQ.setFinishReturn(0);
            riimRiskImportMapper.updateByPrimaryKeySelective(riskImportQ);
            rifiRiskFinishMapper.updateByPrimaryKeySelective(finish);
        } else if ("end".equals(params.get("submitType")) && "B05".equals(params.get("status"))) {
            //运改部终审不通过
            finish.setIsFinish(1);
            RiimRiskImport riskImportQ = new RiimRiskImport();
            BeanUtils.copyBeanProp(riskImportQ, riimImport1);
            riskImportQ.setFinishStatus("A01");
            riskImportQ.setFinishStatusName("草稿");
            riskImportQ.setFinishReturn(0);
            riimRiskImportMapper.updateByPrimaryKeySelective(riskImportQ);
            rifiRiskFinishMapper.updateByPrimaryKeySelective(finish);
            noticeDutyUser(riskImportQ, finish);
        } else if ("end".equals(params.get("submitType")) && "B07".equals(params.get("status"))) {
            RiimRiskImport riskImportQ = new RiimRiskImport();
            BeanUtils.copyBeanProp(riskImportQ, riimImport1);
            if ("不符合结题".equals(finish.getAssessResult())) {
                //运改部领导审核不符合结题
                finish.setIsFinish(1);
                riskImportQ.setFinishStatus("A01");
                riskImportQ.setFinishStatusName("草稿");
                riskImportQ.setFinishReturn(0);
                rifiRiskFinishMapper.updateByPrimaryKeySelective(finish);
                noticeDutyUser(riskImportQ, finish);
                riimRiskImportMapper.updateByPrimaryKeySelective(riskImportQ);
            } else {
                //符合结题、关闭重点风险
                closeRiimImport(riimImport1);
                //关闭风险档案 ,开启结题条件，再打开这一行
//                closeRidcRisk(riimImport1);
                rifiRiskFinishMapper.updateByPrimaryKeySelective(finish);
            }

        } /*else {
            try {
                //下发能力测评
                doIssuedEvaluate(finish);
                //启动结题能力测评流程
                FltdTaskVO taskVO = new FltdTaskVO();
                taskVO.setFlowNo("fengxianjieticeping");
                taskVO.setFlowName("重点风险结题能力测评");
                taskVO.setAcctYear(DateUtils.format(new Date(), "yyyy"));
                taskVO.setQuarterCode(DateUtils.getQuarter(new Date()));
                taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
                XtzyCompany company = companyMapper.selectByPrimaryKey(riimImport1.getDeptCode());
                company = companyMapper.getTopCompany(company.getPathCode(), Short.parseShort("2"));
                taskVO.setCustomCompany(company);
                taskVO.setCompCode(riimImport1.getCompCode());
                taskVO.setCompName(riimImport1.getCompName());
                taskVO.setDeptCode(riimImport1.getDeptCode());
                taskVO.setDeptName(riimImport1.getDeptName());
                taskVO.setBizName(riimImport1.getRiskName());
                String bizDesc = "<" + riimImport1.getRiskName() + ">-重点风险结题能力测评";
                taskVO.setBizDesc(bizDesc);
                taskVO.setBizGuid(finish.getId());
                taskVO.setTaskGuid(riimImport1.getId());
                taskVO.setGroupCondition(taskVO.getAcctYear() + taskVO.getQuarterCode());
                try {
                    fltdProcessService.doStart(taskVO);
                    // 保存日志到数据库
                    AsyncManager.me().execute(AsyncFactory.recordOper(
                            fltdProcessService.getLog("重点风险结题能力测评-流程启动成功", 0, "业务id：" + riimImport1.getId() + "，重点风险id：" + riimImport1.getId(), null)));
                } catch (Exception e) {
                    // 保存日志到数据库
                    AsyncManager.me().execute(AsyncFactory.recordOper(
                            fltdProcessService.getLog("重点风险结题能力测评-流程启动失败", 1, "业务id：" + riimImport1.getId() + "，重点风险id：" + riimImport1.getId() + "， 失败原因： " + e.getMessage(), null)));
                }
            } catch (Exception e) {
                // 保存日志到数据库
                AsyncManager.me().execute(AsyncFactory.recordOper(
                        fltdProcessService.getLog("重点风险结题能力测评-下发异常", 1, e.getMessage(), null)));
            }
        }*/
        return true;
    }

    private void closeRidcRisk(RiimRiskImport riimImport1) {
        try {
            Integer integer = ridcRiskMapper.closeRidcRisk(riimImport1);
        } catch (RuntimeException e) {
            throw new RuntimeException("关闭风险档案失败");
        }
    }

    private void closeRiimImport(RiimRiskImport riimImport1) {

        riimRiskImportMapper.closeImportByHisRiskId(riimImport1.getHisRiskId());
    }

    //生成重点风险结题pdf
    private void updateWord(Map<String, Object> params) {
//        AsyncManager.me().execute(new TimerTask() {
//            @Override
//            public void run() {
        try {
            String finishId = (String) params.get("bizGuid");
            String importId = (String) params.get("taskGuid");
            Map map = riskFinishService.importWord(importId);
            if (map.isEmpty()) {
                log.error("数据为空！");
                throw new Exception("数据为空");
            }
            String sourceModel = "T_RIFI_RISK";
            freeMarkerController.exportPDF(map, "finish.ftl", "fengxianjieti", finishId, sourceModel, true);
        } catch (Exception e) {
            log.error("生成风险结题pdf异常：" + e.getMessage());
        }
//            }
//        });
    }

    public String zhaunhuan(String goal) {
        String result = goal.replaceAll("<", "&lt;");
        String result2 = result.replaceAll(">", "&gt;");
//      String result3 = result2.replaceAll("\'", "&#39;");
        String result4 = result2.replaceAll("\"", "&quot;");
        return result4;
    }

    public void noticeDutyUser(RiimRiskImport riskImport, RifiRiskFinish finish) {
        XtzyUser sysUser = ShiroUtils.getUser();
        FltdTask taskVO = (FltdTask) BeanUtils.initBean(new FltdTask());
        taskVO.setTodoGuid(UUID.randomUUID().toString());
        taskVO.setFlowNo("jietitongzhi");
        taskVO.setFlowName("结题通知");
        taskVO.setAcctYear(DateUtils.format(new Date(), "yyyy"));
        taskVO.setQuarterCode(DateUtils.getQuarter(new Date()));
        taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
        taskVO.setFirstUserCode(sysUser.getUserCode());
        taskVO.setFirstUserName(sysUser.getUserDesc());
        taskVO.setGroupFlag("N");
        taskVO.setBeforeUserCode(sysUser.getUserCode());
        taskVO.setBeforeUserName(sysUser.getUserDesc());
        taskVO.setCurrUserCode(riskImport.getDutyUserCode());
        taskVO.setCurrUserName(riskImport.getDutyUserName());
        taskVO.setCompCode(riskImport.getCompCode());
        taskVO.setCompName(riskImport.getCompName());
        taskVO.setDeptCode(finish.getCompCode());
        taskVO.setDeptName(finish.getCompName());
//        taskVO.setPageUrl("/rifi/notice");
        taskVO.setBizGuid(finish.getId());
        taskVO.setBizName(riskImport.getRiskName());
        taskVO.setBizDesc("<" + riskImport.getRiskName() + ">-风险不符合结题，请重新进行提交。-" + taskVO.getAcctYear() + "年度");
        taskVO.setTodoType("2");
        taskVO.setStatus("open");
        taskVO.setStatusName("进行中");
        taskVO.setFactStartDate(new Date());

        if (fltdTaskService.insert(taskVO) > 0) {
            // 发送通知
            XtzyUser userMsg = new XtzyUser();
            userMsg.setUserCode(riskImport.getDutyUserCode());
            userMsg.setUserDesc(riskImport.getDutyUserName());
            userMsg.setExt1(finish.getCompCode());
            userMsg.setExt2(finish.getCompName());
            userMsg.setExt3("open");
            socketServer.sendMsgToAll(userMsg);
        }

    }

    @Override
    public Map pushFinish(String finishId) {
        Map returnMap=new HashMap();
        returnMap.put("status","1");
        returnMap.put("msg","推送成功");
        try{
            RifiRiskFinish finishParam=new RifiRiskFinish();
            finishParam.setImportGuid(finishId);
            RifiRiskFinish riskFinish=rifiRiskFinishMapper.selectOne(finishParam);
            if(!ObjectUtils.isEmpty(riskFinish)){
                //根据重点风险ID,查询重点风险清单（t_riim_risk_import）
                RiimRiskImport riskImport=new RiimRiskImport();
                riskImport.setId(riskFinish.getImportGuid());
                RiimRiskImport subRiskImport= riimRiskImportMapper.selectOne(riskImport);
                //查询上级单位的重点风险清单
                if(StringUtils.isNotEmpty(subRiskImport.getParentId())){
                    RiimRiskImport parentRiskImport=new RiimRiskImport();
                    parentRiskImport.setId(subRiskImport.getParentId());
                    RiimRiskImport parentImport=riimRiskImportMapper.selectOne(parentRiskImport);
                    if("B09".equals(parentImport.getStatus())){
                        RifiRiskFinish parentFinish=rifiRiskFinishMapper.selectByImportGuid(parentImport.getId());
                        //如果上级风险报告的当前节点为待填报（B01），则执行数据复制、调用上级单位工作流；
                        // 如果上级风险报告的当前节点为待填报（B03、B04、B05、B06、B07），程序结束；
                        //如果上级单位的当前节点为其他，则提示“宝钢股份重点风险档案的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流”
                        if(ObjectUtils.isEmpty(parentFinish)){
                            returnMap.put("status","0");
                            returnMap.put("msg","宝钢股份重点风险档案的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流");
                            return returnMap;
                        }
                        if("B01".equals(parentFinish.getFinishStatus())){
                            RifiRiskFinish updateFinish=new RifiRiskFinish();
                            updateFinish.setId(finishId);
                            updateFinish.setExt5(parentFinish.getId());
                            rifiRiskFinishMapper.updateByPrimaryKey(updateFinish);
                            this.submit(parentFinish,parentImport);

                        }else {
                            returnMap.put("status","0");
                            returnMap.put("msg","宝钢股份重点风险档案的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流");
                            return returnMap;
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("扭转流程异常："+e.getMessage());
            returnMap.put("status","0");
            returnMap.put("msg","扭转流程异常："+e.getMessage());
            e.printStackTrace();
            return returnMap;
        }

        return returnMap;
    }


    private void submit(RifiRiskFinish parentFinish, RiimRiskImport parentImport){
        if(com.baosight.risk.common.utils.StringUtils.isNotEmpty(parentImport.getDutyUserCode())){
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentImport.getDutyUserCode());
            FltdTaskVO paramTask=new FltdTaskVO();
            paramTask.setFlowNo("fengxianjieti");
            paramTask.setBizGuid(parentFinish.getId());
            paramTask.setNodeCode(parentFinish.getFinishStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if(taskList.size()>0){
                FltdTaskVO taskVoParam=new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask=new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);
                    List<XtzyUser> authUsers = (List<XtzyUser>)resultMap.get("authUsers");
                    if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(authUsers)){
                        taskVoParam.setCustomUsers(authUsers);

                        //查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);

                        fltdProcessService.doSubmit(xtzyUser,taskVoParam);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }

    @Data
    private class Sum {
        /**
         * 测量总值
         */
        private String sum;
        /**
         * 测量数量
         */
        private String count;
    }
}
